package com.liu.service.impl;


import com.liu.constant.RedisConstant;
import com.liu.entity.Goods;
import com.liu.entity.Stock;
import com.liu.error.BusinessException;
import com.liu.mapper.GoodsMapper;
import com.liu.mapper.StockMapper;
import com.liu.service.ActivityService;
import com.liu.service.GoodsService;
import com.liu.vo.ActivityVo;
import com.liu.vo.GoodsDetailVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 商品service
 */
@Service
public class GoodsServiceImpl implements GoodsService {

    @Autowired
    private GoodsMapper goodsMapper;

    @Autowired
    private ActivityService activityService;

    @Autowired
    private StockMapper stockMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public List<Goods> listGoods() {
        List<Goods> goodsList = goodsMapper.getGoodsList();
        return goodsList;
    }

    @Override
    public GoodsDetailVo getGoodsById(Long goodsId) {
        System.out.println("数据库查询");
        Goods goods = goodsMapper.selectByPrimaryKey(goodsId);
        if (goods == null) {
            return null;
        }

        //操作获得库存数量
        Stock stock = stockMapper.selectByGoodsId(goodsId);

        GoodsDetailVo goodsDetailVo = new GoodsDetailVo();
        BeanUtils.copyProperties(goods, goodsDetailVo);
        goodsDetailVo.setGoodsId(goodsId);
        goodsDetailVo.setStockNum(stock.getStockNum());

        //获取活动商品信息
        ActivityVo activityVo = activityService.getActivityByGoodsId(goodsId);
        if (activityVo != null && activityVo.getActivityStatus().intValue() != 3) {
            goodsDetailVo.setActivityVo(activityVo);
        }
        return goodsDetailVo;
    }

    @Override
    @Transactional
    public void increaseSales(Long goodsId, Integer amount) throws BusinessException {
        goodsMapper.increaseSales(goodsId, amount);
    }

    @Override
    public GoodsDetailVo getGoodsByIdInCache(Long goodsId) {
        GoodsDetailVo goodsDetailVo = (GoodsDetailVo) redisTemplate.opsForValue().get(RedisConstant.goodsDetail + goodsId);
        if (goodsDetailVo == null) {
            goodsDetailVo = this.getGoodsById(goodsId);
            redisTemplate.opsForValue().set(RedisConstant.goodsDetail + goodsId, goodsDetailVo);
            redisTemplate.expire(RedisConstant.goodsDetail + goodsId, 10, TimeUnit.MINUTES);
        }
        return goodsDetailVo;
    }

}